package push

import (
	"backend/middleware/wx"
	"backend/pkg/logging"
	"backend/pkg/request"
	"backend/pkg/setting"
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/json"
)

func getTpl() {

}

/**
	微信推送push
 */
func wxPush(c *gin.Context, data map[string]interface{}, openid string, tpl string) bool {
	baseUrl := "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s"
	token := wx.GetAccessToken(c)
	fmt.Println(token)
	params := map[string]interface{}{
		"touser":           openid,
		"template_id":      tpl,
		"page":             "index",
		"form_id":          "#",
		"data":             data,
		"emphasis_keyword": "",
	}

	res := request.PostJson(fmt.Sprintf(baseUrl, token), params)
	fmt.Println(res)
	if string(res) != "" {
		var resMap map[string]interface{}
		decoder := json.NewDecoder(bytes.NewBuffer(res))
		decoder.Decode(&resMap)
		fmt.Println(resMap)
		if code, ok := resMap["errcode"]; ok {
			if code == 0 {
				return true
			}

			logging.Fatal(resMap["errmsg"])
			return false
		}

		return false
	}

	return false
}

/**
	客户服务反馈通知
 */
func PushFeedBack(c *gin.Context, content string, tip string, openid string) bool {
	data := map[string]interface{}{
		"keyword1": content,
		"keyword2": tip,
	}

	return wxPush(c, data, openid, setting.FeedBackId)
}
